//
//  WBOAuthViewController.swift
//  weibo
//
//  Created by iobit on 2017/06/30.
//  Copyright © 2017 zhuxu. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBOAuthViewController: UIViewController {

    lazy var webView = UIWebView()
    
    override func loadView() {
        view = webView
        view.backgroundColor = UIColor.white
        // 取消滚动视图，新浪微博返回的授权页面默认就是手机页面
        webView.scrollView.isScrollEnabled = false
        // 设置代理
        webView.delegate = self
        
        title = "新浪微博登录"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(close), isBack: true)
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFill), isBack: false)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        //加载授权页面
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirectURI)"
        guard let url = URL(string: urlString) else {
            print("加载授权页面网页拼接出错")
            return
        }
        // 建立请求
        let request = URLRequest(url: url)
        // 加载请求
        webView.loadRequest(request)
        
    }

    /// 返回按钮监听方法
    func close() {
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    
    /// 自动填充 -- WebView 的注入，直接通过 js 修改本地浏览器中缓存的页面内容
    /// 点击登录按钮，执行submit() 将本地数据提交给服务器
    func autoFill() {
        // 准备js
        let js = "document.getElementById('userId').value = '15928152911';" + "document.getElementById('passwd').value = 'xg15928152911';" //开发者账号
//        let js = "document.getElementById('userId').value = '18810462948';" + "document.getElementById('passwd').value = 'xg15928152911';" //测试账号
        // 让webView执行js
        webView.stringByEvaluatingJavaScript(from: js)
    }
}


// MARK: - UIWebViewDelegate
extension WBOAuthViewController: UIWebViewDelegate {
    
    
    /// webView将要加载请求
    ///
    /// - Parameters:
    ///   - webView: webView
    ///   - request: 要加载的请求
    ///   - navigationType: 导航类型
    /// - Returns: 是否加载request
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
//        print("加载请求---\(request.url?.absoluteString)")
        
        // 判断请求地址中是否包含http://baidu.com，有则不加载百度页面，否则加载
        // request.url?.absoluteString.hasPrefix(WBRedirectURI) 返回的是可选项 Bool(true/false)/nil
        if request.url?.absoluteString.hasPrefix(WBRedirectURI) == false {
            return true
        }
        
        // query 就是url中 ？ 后面的所有部分
        // hasPrefix判断截取的部分是否包含 code= ，不包含则取消授权
        // 取消授权的请求地址格式  http://baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
        if request.url?.query?.hasPrefix("code=") == false{
            print("取消授权")
            close()
        }
        
        // 从query中取出授权码
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        print(code)
        // 通过授权码获取AccessToken
        WBNetWorkManager.shared.loadAccessToken(code: code) { (isSuccess) in
            if !isSuccess {
                SVProgressHUD.showInfo(withStatus: "网络请求失败")
            }else {
                // 发送通知
                NotificationCenter.default.post(name: NSNotification.Name(WBUserLoginSuccessNotification), object: nil)
                
                self.close()
                
            }
        }
        
        return false
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
